﻿
$(function () {
    var _headBackgroundColor = "";
    var _menuBackgroundColor = "";
    var _currentPropertyName = "";
    var submitModel = {};
    new Vue({
        el: '#render_layout',
        data: {
            banners: [],
            hots: [],
            commands: [],
            menus: [],
            specialPlace: [],
            specialArea: [],
            words: [],
            keyWord: ""
        },
        created: function () {

            this.LoadData();
        },
        //挂载后
        mounted: function () {
            var that = this;
            //this.initHomeData();
            this.initBanners();
            this.initCommandProducts();
            this.initHotProducts();
            this.initMenuList();
            this.initSpecialPlace();
            this.initSpecialArea();
            this.initWords();
            //this.LoadData();
            //组件点击选择
            $(document).on('click', '.isComment', function () {
                $('.isComment').css("border", "");
                $(this).css("border", "1px dashed #8b4310");
                var itemName = $(this).attr("itemName");
                var comment = CommentManager.ShopComment.Get(itemName);
                that.ShowCommentProterty(comment);
            });
            //保存设置
            $(document).on('click', '#btn_save', function () {
                that.Save();
            });

            //去设置数据
            $(document).on('click', '.jumpToAddData', function () {
                var url = $(this).attr("url");
                layer.confirm('离开前，保存设置吗？', {
                    btn: ['保存', '不保存']
                }, function () {
                    that.Save();

                    window.parent.location.href = url;

                }, function () {
                    window.parent.location.href = url;
                });
            });

            //基本组件=》右侧BODY区域拖拽注册
            Sortable.create(document.getElementById("foo"), {
                group: {
                    name: "comment",
                    pull: 'clone',
                    put: function (o, evt) {
                        //只允许bar里边的元素拖回来
                        if (evt.el.id == "bar")
                            return true;
                        return false;
                    }
                },
                ghostClass: 'blue-background-class',
                animation: 150,
                onEnd: function (evt) {
                    //判断如果是原区域移动，不进行修改

                    if (evt.to.id == "foo")
                        return false;
                    var comment = CommentManager.ShopComment.Get(evt.item.getAttribute("comment-name"));
                    //evt.item.outerHTML = comment.Template;
                   
                    //动态vue刷新某元素数据
                    var Profile = Vue.extend({
                        data: function () {
                            return {
                                words: that.words,
                                banners: that.banners,
                                hots: that.hots,
                                commands: that.commands,
                                menus: that.menus,
                                specialPlace: that.specialPlace,
                                specialArea: that.specialArea
                            }
                        },
                        template: comment.Template

                    })
                    new Profile().$mount("#bar button[comment-name='" + comment.Name + "']")
                    //如果轮播图，为了让监控触发，轮播插件，手动触发
                    that.banners = [];
                    that.initBanners();
                    that.ShowCommentProterty(comment);
                }
            });
            //右侧BOSY区域=》左侧基本组件
            Sortable.create(document.getElementById("bar"), {
                group: "comment",
                animation: 150,
                ghostClass: 'blue-background-class',
                onEnd: function (evt) {
                    //判断如果是放回左侧，就修改
                    
                    if (evt.to.id == "foo") {
                        //拖回去，消失
                        evt.item.outerHTML = '';
                        //属性HTML消失
                        $("#property_body").html('');
                        //如果是menu,恢复成默认颜色
                      
                        if (evt.item.attributes.itemname.value == "menu") {
                            _menuBackgroundColor = "";
                        }
                    }
                }
            });
            //组合组件=》右侧Head区域拖拽
            Sortable.create(document.getElementById("compose_foo"), {
                group: {
                    name: "compose_comment",
                    pull: 'clone',
                    put: function (e, evt) {
                        if (evt.el.id == "head_layout")
                            return true;
                        return false;
                    }
                },
                ghostClass: 'blue-background-class',
                animation: 150,
                onEnd: function (evt) {
                    //判断如果是原区域移动，不进行修改

                    if (evt.to.id == "compose_foo")
                        return false;
                    //如果已经有了，就不添加了
                    if ($("#head_layout .header").length > 0)
                        return false;
                    var comment = CommentManager.ShopComment.Get(evt.item.getAttribute("comment-name"));
                    //evt.item.outerHTML = comment.Template;
                    $("#head_layout").css("height", "");
                    var Profile = Vue.extend({
                        data: function () {
                            return {
                                words: that.words,
                                banners: that.banners,
                                hots: that.hots,
                                commands: that.commands,
                                menus: that.menus,
                                specialPlace: that.specialPlace,
                                specialArea: that.specialArea
                            }
                        },
                        template: comment.Template
                    })
                    new Profile().$mount("#head_layout button[comment-name='" + comment.Name + "']")
                    //如果轮播图，为了让监控触发，轮播插件，手动触发
                    that.banners = [];
                    that.initBanners();
                    that.ShowCommentProterty(comment);
                }
            });
            //右侧head区域=》基本组件
            Sortable.create(document.getElementById("head_layout"), {
                group: {
                    name: "compose_comment",
                    pull: true,
                    put: function (e, evt) {
                        //如果已经有了，就不添加了
                        if ($("#head_layout .header").length > 0)
                            return false;
                    }
                },
                ghostClass: 'blue-background-class',
                animation: 150,
                onEnd: function (evt) {
                    //判断如果是放回左侧，就修改
                    if (evt.to.id == "compose_foo") {
                        evt.item.outerHTML = '';
                        $("#head_layout").css("height", "2px");
                        //属性HTML消失
                        $("#property_body").html('');
                        //恢复默认颜色
                        _headBackgroundColor = "";
                    }

                }
            });
        },
        watch: {
            'banners': function () {
                this.$nextTick(function () {

                    $(".swiper-banner").swiper({
                        loop: true,
                        autoplay: 3000
                    });
                    var height = $(".swiper-wrapper").height();
                    $(".swiper-slide img").each(function () {
                        $(this).css("height", height + "px");
                    })
                })
            },
            'words': function () {

            }
        },
        //定义方法
        methods: {
            LoadData: function () {
                var that = this;
                $.ajax({
                    type: "GET",
                    url: "/Decorate/GetDesign?r=" + new Date().getTime(),
                    data: null,
                    dataType: "json",
                    success: function (data) {
                        if (data.IsSuccess) {

                            submitModel = data.Data;
                            if (submitModel.DecorateDesign.length > 0) {
                                //加载上次保存的组件

                                var _htmlArr = [];
                                var _temp_template = "";
                                for (var i = 0; i < submitModel.DecorateDesign.length; i++) {
                                    //这里应该是，为组件再赋值一个属性，位置。。暂时先这样
                                    if (submitModel.DecorateDesign[i].Name == "head" && submitModel.DecorateDesign[i].IsRender) {
                                        //加载头部组合组件
                                        _temp_template = CommentManager.ShopComment.Get(submitModel.DecorateDesign[i].Name).Template;
                                        $("#head_layout").html(_temp_template);
                                        $("#head_layout").css("height", "");
                                        if (submitModel.DecorateDesign[i].Color != "") {
                                            _headBackgroundColor = submitModel.DecorateDesign[i].Color;
                                        }
                                    }

                                    if (submitModel.DecorateDesign[i].IsRender && submitModel.DecorateDesign[i].Name != "head") {
                                        _temp_template = CommentManager.ShopComment.Get(submitModel.DecorateDesign[i].Name).Template;
                                        _htmlArr.push(_temp_template);
                                        //特殊处理，暂时如果是head和menu,需要赋值，并给变量颜色赋值

                                        if (submitModel.DecorateDesign[i].Name == "menu" && submitModel.DecorateDesign[i].Color != "") {
                                            _menuBackgroundColor = submitModel.DecorateDesign[i].Color;
                                        }
                                    }

                                }
                                $("#bar").html(_htmlArr.join(''));
                                if (_menuBackgroundColor != "")
                                    $(".menuItem").css("background", _menuBackgroundColor);
                                if (_headBackgroundColor != "")
                                    $(".header").css("background-color", _headBackgroundColor);
                                //动态轮播图高度
                                $(".swiper-banner").swiper({
                                    loop: true,
                                    autoplay: 3000
                                });
                                var height = $(".swiper-wrapper").height();
                                $(".swiper-slide img").each(function () {
                                    $(this).css("height", height + "px");
                                })
                            }


                        } else {
                            layer.alert(data.Message);
                        }
                    },
                    async: false // to make it synchronous
                })

            },
            Save: function () {
                submitModel.DecorateDesign = [];
                var that = this;
                var _renderNameArr = [];
                //组装已渲染的组件
                $(".isComment").each((index, item) => {
                    that.MakeSubmitJson(item);
                    _renderNameArr.push(item.getAttribute("itemname"));
                });
                //组装不渲染的组件
                this.PackageNotRenderComments(_renderNameArr);
                var index = layer.load(1);
                RequestManager.Ajax.Post("/Decorate/Save", submitModel, true, function (data) {
                    layer.close(index);
                    if (data.IsSuccess) {
                        layer.alert("保存成功");

                    } else {
                        layer.alert(data.Message);
                    }
                })
            },
            PackageNotRenderComments: function (renderNameArr) {

                //根据渲染的组件数组，过滤出，不渲染的，求两个数组差集
                //var _tArr = renderNameArr.diff(CommentManager.CommentNames);
                var _tArr = CommentManager.CommentNames.diff(renderNameArr);
                _tArr.forEach((item, index, array) => {
                    submitModel.DecorateDesign.push({
                        Name: item,
                        IsRender: false
                    });
                });

            },
            MakeSubmitJson: function ($node) {
                var commentName = $node.getAttribute("itemname");
                var _model = {
                    Name: commentName,
                    IsRender: true
                };
                if (commentName == "head")
                    _model.Color = _headBackgroundColor;
                if (commentName == "menu")
                    _model.Color = _menuBackgroundColor;
                submitModel.DecorateDesign.push(_model);
            },
            //组件属性展示
            ShowCommentProterty: function (comment) {
                var that = this;
                var propertys = comment.Propertys;
                var hArr = [];
                for (var i = 0; i < propertys.length; i++) {

                    switch (propertys[i].Type) {
                        case "string":
                            hArr.push('<tr><td>组件名称</td><td>' + propertys[i].NameValue + '</td></tr>');
                            break;
                        case "data":
                            hArr.push(this.CheckData(comment.Name, propertys[i], hArr));
                            break;
                        case "backgroundColor":
                            if (comment.Name == "head") {
                                hArr.push('<tr><td>背景颜色</td><td><div vid="comment_head" class="ts"></div></td></tr>');
                            }
                            if (comment.Name == "menu") {
                                hArr.push('<tr><td>背景颜色</td><td><div vid="comment_menu" class="ts"></div></td></tr>');
                            }
                            break;

                    }
                }
                _currentPropertyName = comment.Name;//当前选中组件名称
                $("#property_body").html(hArr.join(''));

                //选中样式
                $('.isComment').css("border", "");
                $(".isComment[itemName='" + _currentPropertyName + "'] ").css("border", "1px dashed #8b4310");

                if ($("#property_body .ts").length > 0) {
                    layui.use('colorpicker', function () {
                        var colorpicker = layui.colorpicker;
                        colorpicker.render({
                            elem: '.ts',
                            change: function (color) {
                                //颜色改变事件
                                that.ColorChangeEvent(color);
                            }
                        });
                    });
                    //再次选中时，如果之前选完颜色后，赋值文本框,再改变背景颜色
                    if (_currentPropertyName == "head") {
                        if (_headBackgroundColor != "") {
                            $(".layui-colorpicker-main input").val(_headBackgroundColor);
                            $(".header").css("background-color", _headBackgroundColor);
                        }

                    }
                    if (_currentPropertyName == "menu") {
                        if (_menuBackgroundColor != "") {
                            $(".layui-colorpicker-main input").val(_menuBackgroundColor);
                            $(".menuItem").css("background", _menuBackgroundColor);
                        }

                    }
                }

            },
            ColorChangeEvent: function (color) {
                if (_currentPropertyName == "head") {
                    _headBackgroundColor = color;
                    //改变背景颜色
                    $(".header").css("background-color", color);
                }
                if (_currentPropertyName == "menu") {
                    _menuBackgroundColor = color;
                    $(".menuItem").css("background", color);
                }
            },
            CheckData: function (name, property, arr) {
                switch (name) {
                    case "head":
                        if (property.Name == '搜索词') {
                            if (this.words && this.words.length > 0) {
                                arr.push(this.GetEditHtml(property.Name, "/SearchWord/List"))
                            }
                            else {
                                arr.push(this.GetJumpHtml(property.Name, "/SearchWord/List"));
                            }

                        }
                        if (property.Name == '轮播图') {
                            if (this.banners && this.banners.length > 0) {
                                arr.push(this.GetEditHtml(property.Name, "/Product/BannerList"))
                            }
                            else {
                                arr.push(this.GetJumpHtml(property.Name, "/Product/BannerList"));
                            }

                        }
                        break;
                    case "keyword":
                        if (this.words && this.words.length > 0) {
                            arr.push(this.GetEditHtml(property.Name, "/SearchWord/List"))
                        }
                        else {
                            arr.push(this.GetJumpHtml(property.Name, "/SearchWord/List"));
                        }
                        break;
                    case "banner":
                        if (this.banners && this.banners.length > 0) {
                            arr.push(this.GetEditHtml(property.Name, "/Product/BannerList"))
                        }
                        else {
                            arr.push(this.GetJumpHtml(property.Name, "/Product/BannerList"));
                        }
                        break;
                    case "menu":
                        if (this.menus && this.menus.length > 0) {
                            arr.push(this.GetEditHtml(property.Name, "/Product/Menu"))
                        }
                        else {
                            arr.push(this.GetJumpHtml(property.Name, "/Product/Menu"));
                        }
                        break;
                    case "productSpecial":
                        if (this.specialPlace && this.specialPlace.length > 0) {
                            arr.push(this.GetEditHtml(property.Name, "/Product/SpecialList"))
                        }
                        else {
                            arr.push(this.GetJumpHtml(property.Name, "/Product/SpecialList"));
                        }
                        break;
                    case "productArea":
                        if (this.specialArea && this.specialArea.length > 0) {
                            arr.push(this.GetEditHtml(property.Name, "/Product/SpecialList"))
                        }
                        else {
                            arr.push(this.GetJumpHtml(property.Name, "/Product/SpecialList"));
                        }
                        break;
                    case "productHot":
                        if (this.hots && this.hots.length > 0) {
                            arr.push(this.GetEditHtml(property.Name, "/Product/Index"))
                        }
                        else {
                            arr.push(this.GetJumpHtml(property.Name, "/Product/Index"));
                        }
                        break;
                    case "productCommand":
                        if (this.commands && this.commands.length > 0) {
                            arr.push(this.GetEditHtml(property.Name, "/Product/Index"))
                        }
                        else {
                            arr.push(this.GetJumpHtml(property.Name, "/Product/Index"));
                        }
                        break;
                }
                return arr;
            },
            GetEditHtml: function (name, url) {
                return '<tr><td>' + name + '</td><td><button type="button" url="' + url + '" class="layui-btn jumpToAddData"><i class="layui-icon">&#xe642;</i> 编辑数据</button></td></tr>';
            },
            GetJumpHtml: function (name, url) {
                return '<tr><td>' + name + '</td><td><button type="button" url="' + url + '" class="layui-btn jumpToAddData"><i class="layui-icon">&#xe608;</i> 去设置</button></td></tr>';
            },

            initSpecialPlace: function () {
                var that = this;
                $.get("/Decorate/GetSpecialPlaceData?type=1&r=" + new Date().getTime(), function (data) {
                    if (data.IsSuccess) {

                        if (data.Data.length > 0) {
                            that.specialPlace = data.Data;
                        }

                    } else {
                        layer.alert(data.Message);
                    }
                })
            },
            initSpecialArea: function () {
                var that = this;
                $.get("/Decorate/GetSpecialPlaceData?type=2&r=" + new Date().getTime(), function (data) {
                    if (data.IsSuccess) {

                        if (data.Data.length > 0) {
                            that.specialArea = data.Data;
                        }

                    } else {
                        layer.alert(data.Message);
                    }
                })
            },
            initMenuList: function () {
                var that = this;
                $.get("/Decorate/GetMenuList?r=" + new Date().getTime(), function (data) {
                    if (data.IsSuccess) {
                        if (data.Data.length > 0) {
                            that.menus = data.Data;
                        }

                    } else {
                        layer.alert(data.Message);
                    }
                })
            },
            initWords: function () {
                var that = this;
                $.get("/Decorate/GetWords?r=" + new Date().getTime(), function (data) {
                    if (data.IsSuccess) {
                        if (data.Data.length > 0) {
                            that.words = data.Data;
                        }

                    } else {
                        layer.alert(data.Message);
                    }
                })
            },
            initHomeData: function () {

                var that = this;
                $.get("/Decorate/GetHomeData?r=" + new Date().getTime(), function (data) {
                    if (data.IsSuccess) {
                        that.mallIndexData = data.Data;

                    } else {
                        layer.alert(data.Message);
                    }
                })
            },
            initBanners: function () {
                var that = this;
                $.ajax({
                    type: "GET",
                    url: "/Decorate/GetBanners?r=" + new Date().getTime(),
                    data: null,
                    dataType: "json",
                    success: function (data) {
                        if (data.IsSuccess) {
                            that.banners = data.Data;

                        } else {
                            layer.alert(data.Message);
                        }
                    },
                    async: false // to make it synchronous
                })
            },
            initHotProducts: function () {
                var that = this;
                $.get("/Decorate/GetHotProducts?r=" + new Date().getTime(), function (data) {
                    if (data.IsSuccess) {
                        that.hots = data.Data;
                    } else {
                        layer.alert(data.Message);
                    }
                })
            },
            initCommandProducts: function () {
                var that = this;
                $.get("/Decorate/GetCommandProducts?r=" + new Date().getTime(), function (data) {
                    if (data.IsSuccess) {
                        that.commands = data.Data;
                    } else {
                        layer.alert(data.Message);
                    }
                })
            }
        }
    })
})



